/* eslint-disable no-console */
const { createVotingServer } = require('..');

const fetch = (...args) => import('node-fetch').then(({ default: fetchImpl }) => fetchImpl(...args));

async function runSmokeTest() {
  const server = createVotingServer({ port: 0 });
  let started = false;
  try {
    const { port } = await server.start();
    started = true;
    const baseUrl = `http://127.0.0.1:${port}`;

    const stateResponse = await fetch(`${baseUrl}/api/state`);
    if (!stateResponse.ok) {
      throw new Error(`无法获取状态，HTTP ${stateResponse.status}`);
    }
    const initialState = await stateResponse.json();
    if (!Array.isArray(initialState.participants) || initialState.participants.length === 0) {
      throw new Error('未找到候选人，无法继续测试');
    }
    const target = initialState.participants[0];

    const voteResponse = await fetch(`${baseUrl}/api/vote`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ participantId: target.id })
    });
    if (!voteResponse.ok) {
      const payload = await voteResponse.json().catch(() => ({}));
      throw new Error(`投票失败：${voteResponse.status} ${payload.reason || ''}`.trim());
    }

    const updatedStateResponse = await fetch(`${baseUrl}/api/state`);
    const updatedState = await updatedStateResponse.json();
    const updatedTarget = updatedState.participants.find((entry) => entry.id === target.id);
    if (!updatedTarget || updatedTarget.votes < (target.votes || 0) + 1) {
      throw new Error('票数未正确累加');
    }

    console.log('✅ 烟雾测试通过：服务能正常响应并累加票数');
  } finally {
    if (started) {
      await server.stop();
    }
  }
}

runSmokeTest().catch((error) => {
  console.error('❌ 烟雾测试失败:', error);
  process.exitCode = 1;
});
